<template>
  <a-layout>
    <a-layout-sider width="200" style="background: #fff">
      <!--            菜单-->
      <a-menu v-model:selectedKeys="state.selectedKeys" style="width: 256px" mode="inline" :open-keys="state.openKeys"
              :items="items" @openChange="onOpenChange" @select="handleSelect">
      </a-menu>
    </a-layout-sider>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-list item-layout="vertical" size="large" :grid="{gutter:20,column:3}" :pagination="pagination"
              :data-source="ebooks">
        <template #renderItem="{ item }">
          <a-list-item key="item.name">
            <template #actions>
          <span v-for="{ icon, text } in actions" :key="icon">
            <component :is="icon" style="margin-right: 8px"/>
            {{ text }}
          </span>
            </template>
            <a-list-item-meta :description="item.description">
              <template #title>
                <a :href="item.href">{{ item.name }}</a>
              </template>
              <template #avatar>
                <a-avatar :src="item.cover"/>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>

    </a-layout-content>
  </a-layout>
</template>

<script lang="ts" setup>
import {
  LaptopOutlined, NotificationOutlined,
  UserOutlined, StarOutlined,
  LikeOutlined, MessageOutlined
} from "@ant-design/icons-vue";
import {ref, onMounted} from "vue";
import axios from "axios";
import {arrayToTree} from "@/utils/tools";
import {h, reactive} from 'vue';
import {ItemType} from 'ant-design-vue';
import type {VueElement} from "vue";
import {AppstoreOutlined, MailOutlined} from '@ant-design/icons-vue';

const pagination = {
  onChange: (page: number) => {
    console.log(page);
  },
  pageSize: 10,
};

const selectedKeys2 = ref(['1']);
const openKeys = ref(['sub1']);

let ebooks = ref([]);

axios.get("http://localhost:8081/ebook").then(
    res => {
      ebooks.value = res.data.data
      console.log(res);
    });

// 优化源码部分
interface Action {
  icon: typeof StarOutlined | typeof LikeOutlined | typeof MessageOutlined;
  text: string;
}

const actions: Action[] = [
  {icon: StarOutlined, text: '156'},
  {icon: LikeOutlined, text: '156'},
  {icon: MessageOutlined, text: '2'},
];

// 定义菜单数据类型
function getItem(
    label: VueElement | string,
    key: string,
    icon?: any,
    children?: ItemType[],
    type?: 'group',
): ItemType {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as ItemType;
}
// 定义菜单状态
const state = reactive({
  rootSubmenuKeys: [],
  openKeys: [],
  selectedKeys: [],
});

// 定义菜单数据
const items: ItemType[] = reactive([
  // 欢迎item
  getItem('欢迎', '/', () => h(MailOutlined)),
]);

// 菜单展开事件
// 菜单展开事件
const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) === -1);
  if (state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    state.openKeys = openKeys;
  } else {
    state.openKeys = latestOpenKey ? [latestOpenKey] : [];
  }
  // 打印第一级目录菜单的id
  // console.log(state.openKeys['0'])
  // 判断state.openKeys['0']是否为undefined
  if (state.openKeys['0'] === undefined) {
      return;
  }
  console.log(state.openKeys['0'])
  // 根据category1Id查询电子书
  axios.get('/ebook/selectByPage', {
    params: {
      page: 1,
      size: 100,
      category1Id: state.openKeys['0']
    }
  }).then(res => {
    ebooks.value = res.data.data.list
  })
};


// 菜单选中事件
const handleSelect = () => {
  console.log(state.selectedKeys)
  // 根据category2Id查询电子书
  axios.get('/ebook', {
    params: {
      page: 1,
      size: 100,
      category2Id: state.selectedKeys[0]
    }
  }).then(res => {
    ebooks.value = res.data.data.list
  })
};

// 创建变量，保存所有类别
const categorys = ref<any[]>([]);

// 查询所有类别
const fetchCategorys = async () => {
  await axios.get('/category/selectByPage', {
    params: {
      page: 1,
      size: 100
    }
  }).then(res => {
    // 将查询到的所有类别，转换为树状结构
    categorys.value = arrayToTree(res.data.data.list);
    // 遍历所有类别，生成菜单数据
    categorys.value.forEach(item => {
      // 生成菜单数据
      items.push(getItem(item.name, item.id, () => h(AppstoreOutlined), [
        ...item.children.map(subItem => getItem(subItem.name, subItem.id))
      ]))
      // 保存所有类别的id，用于判断是否是根菜单
      state.rootSubmenuKeys.push(item.id)
    })
    // 默认展开第一个菜单
    state.openKeys.push(categorys.value[0].id)
  })
}
onMounted(async () => {
  // 调用查询所有电子书的方法
  await fetchEbooks();
  // 调用查询所有类别方法
  await fetchCategorys();
})

// 查询所有电子书
const fetchEbooks = async () => {
  await axios.get('/ebook/selectByPage', {
    params: {
      page: 1,
      size: 30 // 设置较大值，一次性获取所有数据
    }
  }).then(res => {
    ebooks.value = res.data.data.list;
  })
}
</script>
<style scoped>
.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}
</style>
